/**
 * 商品名称选择框用到的公共组件，可以模糊搜索、首字母搜索
 */
import { CrownTwoTone } from '@ant-design/icons';
import React, { useState, useEffect } from 'react';
import { Tooltip } from 'antd';
import { ProFormSelect } from '@ant-design/pro-form';
import { getGoodsListByPage, getZcGoodList } from '@/services/stock-goods/api';
import { useModel } from 'umi';

interface MyProps {
  noStyle: boolean; // true为不显示label，反之，默认显示
  onChange: Function;
  allowClear: boolean;
  filterVal: string; // 用于筛选同科室的商品
  name1: string; // name名称
  value1: string; // 商品id，因为商品名称的列名为goods_name，所以另外传商品id进来，用于定位到某个商品
  scope: string; // 供应范围A:全院，B:本科室 ,
  disabled?: Boolean; // 禁用选项
  onClear?: Function; // 清空事件
  fromTo?: string; // 是否来自中创订单
}

const GoodName: React.FC<MyProps> = (props) => {
  const { noStyle = false, onChange, allowClear, filterVal = '', name1 = 'goods_name', value1, scope = '', disabled, onClear, fromTo = '' } = props;
  // 商品列表
  const [goodsList, setGoodsList] = useState<STOCKGOODSAPI.GoodsItem[]>([]);
  const { initialState } = useModel('@@initialState');

  useEffect(() => {
    const myApi = fromTo === 'zc' ? getZcGoodList : getGoodsListByPage;
    myApi({ current: 1, pageSize: 10000, scope }).then(
      (data: STOCKGOODSAPI.GoodsItemList) => {
        setGoodsList(fromTo === 'zc' ? (data || []) : (data.record_list || []));
      },
    );
  }, []);

  // console.log('shangpn', value1, goodsList)

  const list = goodsList.map((item, key) => {
    if ((filterVal !== '' && item.create_dept_code === filterVal) || filterVal === '') {
      return {
        label: // label显示规则，如果是当前科室的商品，则再商品名前加上👑图标标识
          <Tooltip title={fromTo === 'zc' ? item.goods_name : `【${item.brand_name}】${item.goods_name}`}>
            <div style={{ width: '100%' }}>
              {
                fromTo === 'zc' ? item.goods_name :
                <div>
                  {initialState?.currentUser?.dept_code === item.create_dept_code && <CrownTwoTone />}
                  【{item.brand_name}】{item.goods_name}（{item.goods_py}）
                </div>
              }
              </div>
          </Tooltip>,
        value: item.goods_id,
        list: item.goods_specs_list,
        data: item,
        py: item.goods_py,
        title: fromTo === 'zc' ? item.goods_name : `【${item.brand_name}】${item.goods_name}`,
      };
    }
    return null;
  }).filter(item => item);

  return (
    <ProFormSelect
      name={name1}
      label="商品名称"
      showSearch
      noStyle={noStyle}
      allowClear={allowClear}
      initialValue={value1}
      optionFilterProp="children"
      options={list}
      fieldProps={{
        disabled: disabled,
        optionFilterProp: 'py',
        filterOption: (input, option) => {
          // console.log('(option.py).toLowerCase()', (option.py || '').toLowerCase(), input);
          // 支持大小写首字母匹配 || 名称模糊搜索
          return ((option.py || '').toLowerCase()).includes(input.toLowerCase()) || (option.title || '').includes(input)
        },
        onSelect: (val, opt) => {
          // console.log('val', val, opt.data);
          onChange && onChange(opt.data);
        },
        onClear: () => {
          onClear?.();
        }
      }}
      placeholder="请输入或选择商品名称"
    />
  );
};

export default GoodName;
